package com.youlu.campus.web.community.controller;

import com.youlu.campus.base.interactive.vo.ActivitySignUpRequest;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.UserParticipateActivityInfo;
import com.youlu.campus.entity.VO.req.CheckMobileVO;
import com.youlu.campus.entity.VO.req.QaCommitCommand;
import com.youlu.campus.entity.VO.req.QaInfoReq;
import com.youlu.campus.entity.VO.res.ActivityCsInfoRes;
import com.youlu.campus.entity.VO.res.ActivityHomepageInfoRes;
import com.youlu.campus.entity.VO.res.UserSignInfoRes;
import com.youlu.campus.entity.domain.CsInfoDomain;
import com.youlu.campus.entity.english.vo.request.QueryQaHomeCommand;
import com.youlu.campus.service.activity.ActivityCmsSlideshowService;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.activity.ActivityUserService;
import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import com.youlu.campus.service.qa.ActivityQaInfoService;
import com.youlu.campus.service.qa.UserQaInfoService;
import com.youlu.campus.service.qa.impl.UserQaRankingService;
import com.youlu.campus.web.common.base.RequestContext;
import com.youlu.campus.web.common.utils.CommonUtils;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.Objects;
import java.util.Optional;

@Slf4j
@RestController
public class ActivityPlusController {

    @Autowired
    private UserQaInfoService userQaInfoService;

    @Autowired
    private ActivityQaInfoService activityQaInfoService;
    @Autowired
    private ActivityUserService activityUserService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityCmsSlideshowService activityCmsSlideshowService;

    @Autowired
    private UserQaRankingService userQaRankingService;

    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;


    /**
     * 根据活动ID查询用户答题
     *
     * @param activityId
     * @return
     */
    @GetMapping("/mini-app/plus/user-qa/list")
    public QResult userQaList(@RequestParam("activityId") String activityId) {
        return QResult.success(userQaInfoService.findUserQaInfoByUserIdAndActivityId(RequestContext.getCurUser(), 1, activityId));
    }

    /**
     * 查询获取答题信息
     *
     * @param qaInfoReq
     * @return
     */
    @PostMapping("/mini-app/plus/user-qa/query")
    public QResult qaInfo(@RequestBody @Validated QaInfoReq qaInfoReq, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return QResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        qaInfoReq.setCurrentUser(RequestContext.getCurUser());
        qaInfoReq.setType(2);
        return QResult.success(activityQaInfoService.getQaInfo(qaInfoReq));
    }

    /**
     * 用户活动是否验证过手机号
     *
     * @param activityId
     * @return
     */
    @GetMapping("/mini-app/plus/check-mobiled")
    public QResult checkMobiled(@RequestParam("activityId") String activityId) {
        final String uid = RequestContext.getUserId();
        boolean is = activityUserService.checkMobile(uid, activityId);
        log.info(":>>> 用户:{} 活动:{} 是否验证手机号结果为:{}", uid, activityId, is);
        return QResult.success(is);
    }

    /**
     * 用户报名
     *
     * @param req
     * @return
     */
    @PostMapping("/mini-app/plus/sign-up")
    public QResult signUp(@NotNull @RequestBody CheckMobileVO req, HttpServletRequest request) {
        final String uid = RequestContext.getUserId();
        req.setUserPO(RequestContext.getCurUser());
        req.setPaltform(RequestContext.getCurPlatform());
        req.setAppId(RequestContext.getAppId());
        req.setClientIp(CommonUtils.getRemoteIp(request));
        boolean re = activityUserService.signUp(req);
        if (re) {
            return QResult.success(re);
        }
        return QResult.fail("报名失败");
    }

    /**
     * 检测QA答题
     *
     * @param qaInfoReq
     * @param bindingResult
     * @return
     */
    @PostMapping("/mini-app/plus/user-qa/check")
    public QResult checkQa(@RequestBody @Validated QaInfoReq qaInfoReq, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return QResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        userQaInfoService.checkQaLimit(2, RequestContext.getUserId(), qaInfoReq.getQaInfoId());
        return QResult.success(null);
    }


    /**
     * 答题提交
     *
     * @param
     * @return
     */
    @PostMapping("/mini-app/plus/user-qa/commit")
    public QResult qaCommit(@RequestBody @Validated QaCommitCommand commitCommand, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return QResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        commitCommand.setCurrentUser(RequestContext.getCurUser());
        commitCommand.setType(2);
        return QResult.success(userQaInfoService.doQaCommit(commitCommand));
    }

    /**
     * 查询"活动QQ群"和"联系客服"和"领取福利"
     *
     * @param activityId
     * @return
     */
    @GetMapping("/mini-app/plus/cs-list/query")
    public QResult csInfoList(String activityId) {
        ActivityCsInfoRes res = new ActivityCsInfoRes();
        ActivityInfo activityInfo = activityService.findOne(activityId);
        if(Objects.isNull(activityInfo)){
            return QResult.success(res);
        }
        res.setWelfareRecipientLinker(activityInfo.getWelfareRecipientLinker());
        if(CollectionUtils.isEmpty(activityInfo.getCsInfos())){
            return QResult.success(res);
        }
        Optional<CsInfoDomain> qqOptional = activityInfo.getCsInfos().stream().filter(csInfoDomain -> "QQ".equals(csInfoDomain.getType())).findFirst();
        if(qqOptional.isPresent()){
            CsInfoDomain qqDomain = qqOptional.get();
            res.setQqButtonName(qqDomain.getButtonName());
            res.setQqImageUrl(qqDomain.getImageUrl());
            res.setQqNumber(qqDomain.getNumber());
            res.setQqStatus(qqDomain.getStatus());
            res.setQqUrl(qqDomain.getUrl());
        }
        Optional<CsInfoDomain> wechatOptional = activityInfo.getCsInfos().stream().filter(csInfoDomain -> "wechat".equals(csInfoDomain.getType())).findFirst();
        if(wechatOptional.isPresent()){
            CsInfoDomain wechatDomain = wechatOptional.get();
            res.setCsButtonName(wechatDomain.getButtonName());
            res.setCsImageUrl(wechatDomain.getImageUrl());
            res.setCsNumber(wechatDomain.getNumber());
            res.setCsStatus(wechatDomain.getStatus());
            res.setCsUrl(wechatDomain.getUrl());
        }
        return QResult.success(res);
    }

    /**
     * 查询活动详情
     *
     * @param activityId
     * @return
     */
    @GetMapping("/public/plus/activity/query")
    public QResult activityQuery(String activityId) {
        return QResult.success(activityService.findOne(activityId));
    }

    /**
     * 查询活动轮播图列表
     *
     * @param activityId
     * @return
     */
    @GetMapping("/public/plus/cms-list/query")
    public QResult cmsInfoList(String activityId) {
        ActivityHomepageInfoRes res = new ActivityHomepageInfoRes();
        ActivityInfo activity = activityService.findOne(activityId);
        res.setHeaderHeight(activity.getHeaderHeight());
        res.setHeaderImageMode(activity.getHeaderImageMode());
        res.setHeaderImageUrl(activity.getHeaderImageUrl());
        res.setDetail(activity.getDetail());
        res.setRewardsDetail(activity.getRewardsDetail());
        res.setSponsorDetail(activity.getSponsorDetail());
        res.setName(activity.getName());
        res.setH5OfficialQrcode(activity.getH5OfficialQrcode());
        res.setCmsSlideshowList(activityCmsSlideshowService.findByActivityId(activityId));
        return QResult.success(res);
    }

    /**
     * 查询用户分数
     *
     * @param activityId
     * @return
     */
    @GetMapping("/mini-app/plus/user-qarank/query")
    public QResult cmsGradeList(String activityId) {
        return QResult.success(userQaRankingService.findByUser(RequestContext.getCurUserId(), activityId));
    }

    /**
     * 查询用户报名信息
     *
     * @param activityId
     * @return
     */
    @GetMapping("/mini-app/plus/user-sign/query")
    public QResult userSignInfo(String activityId) {
        UserParticipateActivityInfo signInfo = userParticipateActivityInfoService.findByUserIdActivityId(RequestContext.getCurUserId(), activityId);
        UserSignInfoRes res = new UserSignInfoRes();
        if (Objects.nonNull(signInfo)) {
            res.setUniversityId(signInfo.getUniversityId());
            res.setName(signInfo.getName());
            res.setUniversityName(signInfo.getUniversityName());
            res.setUpdateNameCount(signInfo.getUpdateNameCount());
            res.setSigned(Boolean.TRUE);
            res.setMobile(signInfo.getMobile());
        }
        return QResult.success(res);
    }

    /**
     * 查询分数排行榜
     *
     * @param activityId
     * @param qaId
     * @return
     */
    @GetMapping("/mini-app/plus/grade-ranking/query")
    public QResult gradeRanking(String activityId, String qaId) {
        return QResult.success(userQaRankingService.findByActivityidQaid(activityId, qaId));
    }

    /**
     * 更新用户报名信息
     *
     * @param activitySignUpRequest
     * @return
     */
    @PostMapping("/mini-app/plus/update/userinfo")
    public QResult updateUserInfo(@RequestBody ActivitySignUpRequest activitySignUpRequest) {
        activitySignUpRequest.setUserId(RequestContext.getUserId());
        userParticipateActivityInfoService.updateUserInfo(activitySignUpRequest);
        return QResult.success(null);
    }

    @GetMapping("/mini-app/plus/check/userinfo")
    public QResult checkUserInfo(@RequestParam String activityId) {
        userParticipateActivityInfoService.checkUserInfoSignUp(RequestContext.getUserId(), activityId);
        return QResult.success(null);
    }

    @PostMapping("/mini-app/plus/competition/qa-my")
    public QResult qaMy(@RequestBody @Validated QueryQaHomeCommand queryQaHomeCommand, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return QResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        queryQaHomeCommand.setCurrentUser(RequestContext.getCurUser());
        return QResult.success(userQaInfoService.findByUserIdAndScore(queryQaHomeCommand));
    }

    /**
     * 获取活动详情
     *
     * @param id
     * @return
     */
    @GetMapping("/mini-app/plus/activity-detail")
    public QResult qaMy(@RequestParam("id") String id) {
        return QResult.success(activityService.findOne(id));
    }

}
